package web.login.bo;

import java.util.List;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import web.login.dao.LoginDao;
import web.login.entity.Login;

@Service(value="forgotPasswordBO")
public class ForgotPasswordBO {

	private final Log log = LogFactory.getLog(ForgotPasswordBO.class);
	
	@Autowired
	private LoginDao loginDao;
	
	public LoginDao getLoginDao() {
		return loginDao;
	}

	public void setLoginDao(LoginDao loginDao) {
		this.loginDao = loginDao;
	}
	
	public boolean getUserDetailsAndMail(String userName,final String senderMail, final String senderPass)
	{
		log.info("INSIDE ForgotPasswordBO getUserDetailsAndMail METHOD");
		boolean status = false;
		List<Login> logins =  loginDao.getAllLogin();
		for(Login login:logins)
		{
			if(userName.equalsIgnoreCase(login.getUsername()))
			{
				//initiate sendMail to mail password to the email
				String toEmailId = login.getUserRole();
				String passWord = login.getPassword();
				status = this.sendMail(userName,toEmailId,passWord,senderMail,senderPass);
			}
				
		}
		return status;
	}
	
	public boolean sendMail(String toUsername,String toMailId,String forgotPassWord,final String senderMail, final String senderPass)
	{
		log.info("INSIDE ForgotPasswordBO sendMail METHOD");
		final String fromUsername = senderMail;
		Properties properties = new Properties();
		properties.put("mail.smtp.auth", "true");
		properties.put("mail.smtp.starttls.enable", "true");
		properties.put("mail.smtp.host", "smtp.gmail.com");
		properties.put("mail.smtp.port", "587");
		
		Session session= Session.getInstance(properties, new Authenticator() 
			{
				protected PasswordAuthentication getPasswordAuthentication()
				{
					return new PasswordAuthentication(fromUsername, senderPass);
				}
			});
		
		try
		{
			Message message = new MimeMessage(session);
			message.setFrom(new InternetAddress(senderMail));
			message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toMailId));
			message.setSubject("Testing JAVA MAIL");
			message.setText("Dear "+toUsername+","+"\n\n Your existing password for commonApp is :"+forgotPassWord+"\n\n Regards,"+"\n\n Common App Team");
			Transport.send(message);
			return true;
		}
		catch (Exception e) 
		{
			e.printStackTrace();			
			return false;
		}
	
	}
}
